import { Component, OnInit } from '@angular/core';
import { Carousel } from '../../model/carousel';
import { NewsService } from '../../service/news.service';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { CarouselService } from '../../service/carousel.service';
import { ConfigService } from '../../service/config.service';

@Component({
  selector: 'app-editcarousel',
  templateUrl: './editcarousel.component.html',
  styleUrls: ['./editcarousel.component.css']
})
export class EditcarouselComponent implements OnInit {
  carousel:Carousel;
  parm:string;
  selectedFile:string;
  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private configservice:ConfigService,//图片问题解决
    private carouselservice:CarouselService
  ) {
    this.carousel=new Carousel();
    this.parm=this.routerinfo.snapshot.params['id'];
   }

  ngOnInit() {
    if(this.parm=='add'){ 
    }
     else{
      this.getCarousel(this.parm);
     }
  }
  

  save(){
    console.dir(this.carousel);
    if(this.parm=='add'){
      this.addCarousel();
    }
    else{
      this.updateCarousel();
    }
  //   this.carouselservice.addCarousel(this.carousel)
  //   .then((flag:boolean)=>{
  //  if(flag==true){
  //   alert('成功');
  //  }
  //  else{
  //    alert('失败');
  //      }
  //   })
  }

  goBack(){
    this.router.navigate(['uploadfile']);
    }

  onFileChanged(event) {
    this.selectedFile = event.target.files[0];
    //this.onUpload();
  }

  onUpload() {
    // upload code goes here
    const uploadData = new FormData();
    uploadData.append('file', this.selectedFile);
    //this.http.post('https://39.108.155.242/manage/fileUpload',uploadData).subscribe(alert(data);
    //图片问题解决this.http.post('https://localhost/manage/fileUpload',uploadData).subscribe((data:any)=>{
    this.http.post(this.configservice.host+'/manage/fileUpload',uploadData).subscribe((data:any)=>{  
      //console.log(JSON.stringify(data));
      //let host="https://39.108.155.242/public/";
      //let host="http://localhost/public/";  图片问题解决
      //this.carousel.pic=host+data.pic;  图片问题解决
      this.carousel.pic=data.pic;  //图片问题解决
    },(err:HttpErrorResponse)=>{
      console.log(err.message);
    }
  )
  }

  private addCarousel(){
    this.carouselservice.addCarousel(this.carousel)
    .then((flag:boolean)=>{
     if(flag==true){
       this.goBack();
     }
     else{
       alert('保存异常，请刷新后重试');
     }
    })
   }

   private updateCarousel(){
    this.carouselservice.updateCarousel(this.carousel)
    .then((flag:boolean)=>{
     if(flag==true){
       this.goBack();
     }
     else{
       alert('保存异常，请刷新后重试');
     }
    })
  }

  private getCarousel(id:string){
    this.carouselservice.getCarousel(id).then((data:Carousel)=>{
     if(data){
    this.carousel=data;
     }
     else{
       alert("通讯异常，请刷新后重试");
     }
    })
  }


  
}